import 'package:flutter/material.dart';

import '../../api/OrderApi.dart';


class DevicePage extends StatefulWidget {
  @override
  _DevicePageState createState() => _DevicePageState();
}

class _DevicePageState extends State<DevicePage> {
  final OrderApi _orderApi = OrderApi();
  List<Map<String, dynamic>> deviceList = [];
  bool isLoading = true;
  String errorMessage = '';


  @override
  void initState() {
    super.initState();
    _fetchOrders(); // 页面初始化时调用接口
  }

  void _fetchOrders() async {
    try {
      final response = await _orderApi.getDevice();
      print("API Response: $response");

      if (response['code'] == 200) {
        // 关键修改：显式转换每个元素的类型
        final rows = response['data'] ?? [];
        setState(() {
          deviceList = List<Map<String, dynamic>>.from(rows);
          isLoading = false;
        });
      } else {
        setState(() {
          errorMessage = '请求数据失败: ${response['msg']}';
          isLoading = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请求数据失败: ${response['msg']}')),
        );
      }
    } catch (e) {
      setState(() {
        errorMessage = '请求发生异常: $e';
        isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('请求数据失败: $e')),
      );
    }
  }

  void _showMenu(BuildContext context, int index) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Center(
          child: Material(
            type: MaterialType.transparency,
            child: Container(
              width: 250,
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                      _editDevice(index);
                    },
                    style: ElevatedButton.styleFrom(
                      minimumSize: Size(double.infinity, 40),
                      fixedSize: const Size(150, 50), // 宽度200，高度50
                    ),
                    child: Row(
                      children: [
                        Icon(Icons.edit),
                        SizedBox(width: 10),
                        Text('编辑'),
                      ],
                    ),
                  ),
                  SizedBox(height: 10),
                  ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                      _takeOffline(index);
                    },
                    style: ElevatedButton.styleFrom(
                      minimumSize: Size(double.infinity, 40),
                      fixedSize: const Size(150, 50), // 宽度200，高度50
                    ),
                    child: Row(
                      children: [
                        Icon(Icons.power_off),
                        SizedBox(width: 10),
                        Text('下架'),
                      ],
                    ),
                  ),
                  SizedBox(height: 10),
                  ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                      _deleteDevice(index);
                    },
                    style: ElevatedButton.styleFrom(
                      fixedSize: const Size(150, 50), // 宽度200，高度50
                      minimumSize: Size(double.infinity, 40),
                    ),
                    child: Row(
                      children: [
                        Icon(Icons.delete),
                        SizedBox(width: 10),
                        Text('删除'),
                      ],
                    ),
                  ),
                  SizedBox(height: 5),
                  TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    style: ElevatedButton.styleFrom(
                      fixedSize: const Size(150, 60), // 宽度200，高度50
                    ),
                    child: Text('取消'),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  void _editDevice(int index) {
    print('编辑设备: ${deviceList[index]['name']}');
    // 实际编辑逻辑
  }

  void _takeOffline(int index) {
    print('下架设备: ${deviceList[index]['name']}');
    // 实际下架逻辑
  }

  void _deleteDevice(int index) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('确认删除'),
          content: Text('确定要删除 ${deviceList[index]['name']} 吗？'),
          actions: [
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            TextButton(
              child: Text('删除'),
              onPressed: () {
                setState(() {
                  deviceList.removeAt(index);
                });
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('设备管理'),
      ),
      body: ListView.builder(
        itemCount: deviceList.length,
        itemBuilder: (context, index) {
          final device = deviceList[index];
          return Card(
            margin: EdgeInsets.all(10),
            child: Container(
              padding: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        device['name'],
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      ElevatedButton(
                        onPressed: () => _showMenu(context, index),
                        child: Text('操作'),
                      ),
                    ],
                  ),
                  SizedBox(height: 10),
                  Row(
                    children: [
                      Icon(Icons.device_hub),
                      SizedBox(width: 5),
                      Text('类型: ${device['type']}'),
                    ],
                  ),
                  Row(
                    children: [
                      Icon(device['status'] == '在线'
                          ? Icons.check_circle
                          : Icons.error),
                      SizedBox(width: 5),
                      Text(
                        '状态: ${device['status']}',
                        style: TextStyle(
                          color: device['status'] == '在线'
                              ? Colors.green
                              : Colors.red,
                        ),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Icon(Icons.location_on),
                      SizedBox(width: 5),
                      Text('位置: ${device['location']}'),
                    ],
                  ),
                  Row(
                    children: [
                      Icon(Icons.access_time),
                      SizedBox(width: 5),
                      Text('最后在线: ${device['lastSeen']}'),
                    ],
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
